// 搜索
import {setCache, getCache, removeCache, setTempCache} from '../../utils/localStorage.js'

const search = {
	state: {
		showSearchPanel: false,		// 显示搜索页
		oldRecordsMaxLength: 10,	// 历史搜索保留长度 默认 10
		oldSearchRecords: [],			// 历史搜索
		hotSearchRecords: []			// 热门搜索
	},
	mutations: {
		'SET_SHOW_SEARCH_PANEL': (state, newVal) => {
			state.showSearchPanel = newVal
		},
		'SET_OLD_SEARCH_RECORDS': (state, newVal) => {
			state.oldSearchRecords = newVal
		},
		'SET_HOT_SEARCH_RECORDS': (state, newVal) => {
			state.hotSearchRecords = newVal
		}
	},
	actions: {
		setShowSearchPanel: ({commit, state}, newVal) => {
			return commit('SET_SHOW_SEARCH_PANEL', newVal)
		},
		setOldSearchRecords: ({commit, state}, newVal) => {
			// newVal 为 obj
			let history = getCache('oldSearchRecords')
			if (!history) {
				console.log('缓存没有 oldSearchRecords 记录')
				history = []
			}
			const has = history.includes(newVal)
			// 队列 先进先出
			if (!has) {
				console.log(`缓存没有 ${newVal} 记录`)
				if (history.length >= state.oldRecordsMaxLength) {
					history.pop()
				}
				history.unshift(newVal)
				console.log(`缓存记录`+history)
				setCache('oldSearchRecords', [...new Set(history)])
			}
			return commit('SET_OLD_SEARCH_RECORDS', history)
		},
		setHotSearchRecords: ({commit, state}, newVal) => {
			// newVal 为 array
			if (Array.isArray(newVal)) {
				setTempCache('hotSearchRecords', newVal)
				return commit('SET_HOT_SEARCH_RECORDS', newVal)
			}
		}
	}
}

export default search